package com.sojson.util.encrypt.bothway.alike.aes;
 
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.sojson.util.HexUtil;
 
/**
 * AES双向加解密工具类
 * 
 * @author liu
 * @date 2024-05-29
 */
public class AesUtil {

    private static final String AES = "AES";

    private static final String ALGORITHMSTR = "AES/ECB/PKCS7Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 加密为Base64字符串
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptToBase64(String data, String key) throws Exception {
        // 加密
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), AES);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        byte[] crypted = cipher.doFinal(data.getBytes());

        // 转为Base64字符串
        return Base64.encodeBase64String(crypted);
    }

    /**
     * 加密为16进制字符串
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptToHex(String data, String key) throws Exception {
        // 将16进制字符串转字节数组
        byte[] a = HexUtil.hexString2Bytes(data);

        // 加密
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), AES);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        byte[] crypted = cipher.doFinal(a);

        // 将字节数组转16进制字符串
        return HexUtil.toHex(crypted);
    }

    /**
     * 解密Base64字符串
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptByBase64(String data, String key) throws Exception {
        // 解密Base64字符串
        byte[] decodeBase64 = Base64.decodeBase64(data);

        // 解密
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), AES);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, skey);
        byte[] output = cipher.doFinal(decodeBase64);

        // 返回字符串
        return new String(output);
    }

    /**
     * 解密16进制字符串
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptByHex(String data, String key) throws Exception {
        // 解密
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), AES);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, skey);
        byte[] output = cipher.doFinal(HexUtil.parseHex(data));

        // 将字节数组转16进制字符串
        return HexUtil.bytesToHexString(output);
    }

}